import {Component, OnInit, Input} from "@angular/core";
import "datatables";
import {FormBuilder, FormGroup} from "@angular/forms";
import {UIModifyInfo} from "./ui-modify-info.class";
import {UIModifyService} from "./ui-modify.service";
import {politicalStatuses} from 'app/constants/politicalStatuses'
import {CONFIGS} from '../datepicker/datepicker-config.class';


@Component({
  selector: 'ui-modify',
  templateUrl: 'ui-modify.component.html',
  styleUrls: ['ui-modify.component.scss'],
  providers: [UIModifyService]
})
export class UIModifyComponent implements OnInit {
  @Input() type: string;
  @Input() userListUrl = '/water/userInfoSub/getInfoOfUser';
  @Input() userinfoUrl: string;//原信息
  @Input() userinfoNewUrl: string;
  // @Output() public onSelected: EventEmitter<any> = new EventEmitter();

  private _uiModifyUrl = '/water/userInfoSub/modifyPersonaInfo';
  private uiModifyForm: FormGroup;
  private isModifying: boolean = false;
  private uiModifyInfo: UIModifyInfo = new UIModifyInfo();
  private uiModifyNewInfo: UIModifyInfo = new UIModifyInfo();
  private politicalStatuses = politicalStatuses;
  private uiInfo: any = {};
  private _errorMsg: string;
  private isVerifying: boolean = false;
  private dateInfo: any = {};

  public options: any = CONFIGS;

  private validationMessages = {
    //TODO 补全校验规则
  };

  private formErrors = {
    'companyName': '',
    'bizLicense': '',
    'registeredAddress': '',
    'legalRepresentative': ''
  };

  constructor(private _fb: FormBuilder, private _uiModifyService: UIModifyService) {
  }

  ngOnInit() {
    if (this.type === 'company') {
      this.initSelect2();
    } else {
      this.getUserInfo();
      this.getUserNewInfo();
    }
    this.buildForm();
  }

  private initSelect2() {
    let data: any = [];
    this._uiModifyService.getUserList(this.userListUrl).then(res => {
      let users = res.data;
      for (let i = 0; i < users.length; i++) {
        let item: any = {};
        item.id = users[i].ids;
        item.text = users[i].name + '-' + users[i].idcard;
        data.push(item);
      }

      jQuery('#userList').select2({
        data: data
      });
    });
  }

  buildForm(): void {

    this.uiModifyForm = this._fb.group(
      {
        'userInfoSub_name': [this.uiModifyNewInfo.name],
        'userInfoSub_address': [this.uiModifyNewInfo.address],
        'userInfoSub_government': [this.uiModifyNewInfo.government],
        'userInfoSub_telephone': [this.uiModifyNewInfo.telephone],
        'userInfoSub_idcard': [this.uiModifyNewInfo.idcard],
        'userInfoSub_birthday': [''],
        'userInfoSub_sex': [this.uiModifyNewInfo.sex],
      }
    );
    this.uiModifyForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set validation messages now
  }

  setDate(): void {
    // Set today date using the setValue function
    let date = new Date();
    this.uiModifyForm.setValue({
      userInfoSub_birthday: {
        date: {
          year: date.getFullYear(),
          month: date.getMonth() + 1,
          day: date.getDate()
        }
      }
    });
  }

  onValueChanged(data?: any) {
    // if (!this.uiModifyForm) { return; }
    // const form = this.uiModifyForm;
    // for (const field in this.formErrors) {

    //   this.formErrors[field] = '';
    //   const control = form.get(field);

    //   if (control && control.dirty && !control.valid) {
    //     const messages = this.validationMessages[field];
    //     for (const key in control.errors) {
    //       this.formErrors[field] += messages[key] + ' ';
    //     }
    //   }
    // }
  }

  public addUserinfoModify(action: string): void {

    this.uiInfo = this.uiModifyForm.value;
    this.uiInfo.userInfoSub_ids = this.uiModifyInfo.ids;
    this.uiInfo.action = action;
    this.uiInfo = Object.assign(this.uiInfo, this.dateInfo);
    this._uiModifyService.submit(this._uiModifyUrl, this.uiInfo)
      .then(res => {
        if (res.status === "success") {
          if (this.uiInfo.action == "submit") {
            this.isVerifying = true;
          }
          if (this.uiModifyInfo.idcard == this.uiInfo.userInfoSub_idcard) {
            jQuery('#newIdCard').css('color', '#000000');
          } else {
            jQuery('#newIdCard').css('color', '#93D4E7');
          }
          if (this.uiModifyInfo.name == this.uiInfo.userInfoSub_name) {
            jQuery('#newName').css('color', '#000000');
          } else {
            jQuery('#newName').css('color', '#93D4E7');
          }
          if (this.uiModifyInfo.address == this.uiInfo.userInfoSub_address) {
            jQuery('#newAddress').css('color', '#000000');
          } else {
            jQuery('#newAddress').css('color', '#93D4E7');
          }
          if (this.uiModifyInfo.government == this.uiInfo.userInfoSub_government) {
            jQuery('#newGovernment').css('color', '#000000');
          } else {
            jQuery('#newGovernment').css('color', '#93D4E7');
          }
          if (this.uiModifyInfo.telephone == this.uiInfo.userInfoSub_telephone) {
            jQuery('#newTelephone').css('color', '#000000');
          } else {
            jQuery('#newTelephone').css('color', '#93D4E7');
          }
          if (this.uiModifyInfo.sex == this.uiInfo.userInfoSub_sex) {
            jQuery('#newsex').css('color', '#000000');
          } else {
            jQuery('#newsex').css('color', '#93D4E7');
          }
          if (this.uiModifyInfo.birthday == this.uiInfo.userInfoSub_birthday) {
            jQuery('#newBirthday').css('color', '#000000');
          } else {
            jQuery('#newBirthday').css('color', '#93D4E7');
          }

        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  private getUserInfo() {
    this._uiModifyService.getUserInfo(this.userinfoUrl)
      .then(res => {
        if (res.status === "success") {
          this.uiModifyInfo = res.data;
          if (this.uiModifyInfo.verified === "'待审核'") {
            this.isVerifying = true;
          }
          this.buildForm();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  private getUserNewInfo() {
    this._uiModifyService.getUserInfo(this.userinfoNewUrl)
      .then(res => {
        if (res.status === "success") {
          this.uiModifyNewInfo = res.data;
          if (this.uiModifyNewInfo.verified === "待审核") {
            this.isVerifying = true;
          }
          // setTimeout(this.annotated(), 1000);
          this.buildForm();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  getUserForComp() {
    this.disableAllBtns();

    let userList: any = document.getElementById('userList');
    this._uiModifyService.getUserInfoOfCompany(this.userinfoUrl, userList.value)
      .then(res => {
        if (res.status === "success") {
          this.uiModifyInfo = res.data;
          this.buildForm();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });

    this._uiModifyService.getUserInfoOfCompany(this.userinfoNewUrl, userList.value)
      .then(res => {
        if (res.status === "success") {
          this.uiModifyNewInfo = res.data;
          if (this.uiModifyNewInfo.verified == "待审核") {
            this.isVerifying = true;
          }
          // setTimeout(this.annotated(), 3000);
          this.buildForm();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });

  }

  annotated() {
    if (this.uiModifyNewInfo.verified == "待审核" || this.uiModifyNewInfo.verified == "未提交") {
      if (this.uiModifyInfo.idcard != this.uiModifyNewInfo.idcard) {
        jQuery('#newIdCard').css('color', '#93D4E7');
      } else {
        jQuery('#newIdCard').css('color', '#000000');
      }

      if (this.uiModifyInfo.name != this.uiModifyNewInfo.name) {
        jQuery('#newName').css('color', '#93D4E7');
      } else {
        jQuery('#newName').css('color', '#000000');
      }
      if (this.uiModifyInfo.address != this.uiModifyNewInfo.address) {
        jQuery('#newAddress').css('color', '#93D4E7');
      } else {
        jQuery('#newAddress').css('color', '#000000');
      }
      if (this.uiModifyInfo.government != this.uiModifyNewInfo.government) {
        jQuery('#newGovernment').css('color', '#93D4E7');
      } else {
        jQuery('#newGovernment').css('color', '#000000');
      }
      if (this.uiModifyInfo.telephone != this.uiModifyNewInfo.telephone) {
        jQuery('#newTelephone').css('color', '#93D4E7');
      } else {
        jQuery('#newTelephone').css('color', '#000000');
      }
      if (this.uiModifyInfo.sex != this.uiModifyNewInfo.sex) {
        jQuery('#newsex').css('color', '#93D4E7');
      } else {
        jQuery('#newsex').css('color', '#000000');
      }
    } else {
      jQuery('.update').css('color', '#000000');
    }
  }

  onDateChanged(event: any, type: string) {
    this.dateInfo[type] = this.date2String(event.date);
  }

  // updateDateRange(event, type:string) {
  //   this.dateInfo[type] = this.date2String(event.date);
  // }

  private date2String(date: any): string {
    if (Object.keys(date).length === 0 || date === null || date === undefined || (date.year == 0 && date.month == 0 && date.day == 0)) {
      return null;
    }

    let str = date.year + '-';
    if (date.month < 10) {
      str += '0';
    }
    str += date.month + '-';

    if (date.day < 10) {
      str += '0';
    }
    str += date.day;
    return str;
  }

  private disableAllBtns() {
    this.isModifying = this.isVerifying = false;
  }
}
